/*
 追加报价/测算到合同

 如果业务机会的执行公司类型为Maccura 选择业务机会的客户下 生效未终止 结束日期>今天的合同
 如果业务机会的执行公司类型不为Maccura 选择业务机会的执行公司下 生效未终止 结束日期>今天的合同

*/
public without sharing class AppendReagendProductController{
    
    public String oppId {get;set;}//业务机会ID
    public String qid {get;set;}//报价ID;
    public String mcid {get;set;}//测算ID;
    public List<SelectOption> cons {get;private set;}//要关联的合同
    public String selectedCon  {get;set;}//选择的合同
    
    public List<QuoteProduct__c> qProducts;//报价产品

    public List<Measure_Calculate_Product__c> mcProducts;//测算产品
    public Map<String ,String> qps ;
    public String backId {get;private set;}///是否可以保存

    public Map<Id,Contract__c> optionsConMap ;///可选择的合同

    public String msg  {get;set;}//消息
    public Opportunity opp ;////业务机会
    public Quote q ;//报价

    public Boolean isShouldLink {get;set;}//是否可以关联
    
    public AppendReagendProductController(){
    
        oppId = System.currentPageReference().getParameters().get('oppid');
        
        qid =  System.currentPageReference().getParameters().get('qid');

        mcid =  System.currentPageReference().getParameters().get('mcid');

        backId = qid == null ? mcid == null ? oppId : mcid :qid;
        cons =  new List<SelectOption>();
        qps = new Map<String ,String>();
        msg = '';
        isShouldLink = true;


    }    

    public void init(){
        
        ///
        Map<Id,String> cs = new Map<Id,String>();//保存合同的
        //查询客户
        opp = [select AccountId,ExecutiveCompany__c,ExecutiveCompany__r.RecordType.DeveloperName,StageName from Opportunity where Id =: oppId];
        Id cId = opp.ExecutiveCompany__r.RecordType.DeveloperName == 'Maccura' ? opp.AccountId : opp.ExecutiveCompany__c;
        if(qid !=null)q = [select Id , Contract__c ,StageName__c,Type__c,Status from Quote Where Id =:qid];
        if(q != null && q.Status != '已批准'  && q.Type__c !='试剂报价' ){

            isShouldLink = false;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'已经批准的试剂报价才能追加合同'));
            return;

        }
         Measure_Calculate__c mc = null ;
        if(mcid!=null)  mc = [select Id , Status__c from Measure_Calculate__c where Id =:mcid];
        if ( mc != null && mc.Status__c != '审批成功') {
           isShouldLink = false;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'已经审批通过的测算才能追加合同'));
            return;
 
        }
        //查询合同
            cons.add(new SelectOption('', System.Label.Option_None));

        if (cId == null) {

             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,opp.ExecutiveCompany__r.RecordType.DeveloperName == 'Maccura' ? '报价对应业务机会的"客户"为空!': '报价对应业务机会的"执行公司"为空!'));
             return;

        }

         Date d = Date.today();
        for(Contract__c c: [select Id,Name,Account__c from Contract__c where Status__c = '已生效' And EndDate__c >:d And Account__c =: cId and Stopped__c = false]){
        	cs.put(c.Id,c.Name);
            //选项
            cons.add(new SelectOption(c.Id, c.Name));

        }

       

      
   
    
    }
    public void appendMeasrueCalcProduct(){
          ///查询测算产品
        mcProducts = [select product__c,Product__r.Name,Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c, SalesPriceWT__c from Measure_Calculate_Product__c where Measure_Calculate__c =:mcid and Product__r.Category0__c != '仪器'];
        for(Measure_Calculate_Product__c mcp: mcProducts){
            qps.put(mcp.Product__c ,mcp.Product__c);
        }

        List<ContractProduct__c> newCps = new List<ContractProduct__c>(); 
            Set<Id> temp = new Set<Id>();
            List<Measure_Calculate_Product__c> exitsList = new List<Measure_Calculate_Product__c>();
                if(selectedCon == null){//如果没有选择合同
                     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请选择要关联的合同!'));
                }else{

                     for(ContractProduct__c cp: [select Product__c,Product__r.Name from ContractProduct__c where contract__c =: selectedCon]){
                        if(qps.containsKey(cp.Product__c)){
                            temp.add(cp.Product__c);
                        }   
                    }

                   
                    Id rtShiji = Utils.getRecordTypeIdByDevNameAndObjName('ReagentContractProduct','ContractProduct__c');

                   Contract__c c = [select Id,AddContractProduct__c from Contract__c where Id =: selectedCon];
                   c.AddContractProduct__c = true;
                    
                     for(Measure_Calculate_Product__c mcp : mcProducts){
                     
                         if (temp.contains(mcp.Product__c)) {
                            msg += mcp.Product__r.Brand__c +'-'+ mcp.Product__r.Name +'-' +mcp.Product__r.Spec__c+'*'+mcp.Product__r.SerialNo__c + ';\r\n';
                           exitsList.add(new Measure_Calculate_Product__c(Id=mcp.Id,AppendState__c='与合同产品重复，未追加'));    

                             continue;
                         }else{
                           ContractProduct__c newCp = new ContractProduct__c();
                                newCp.Contract__c = selectedCon;
                                newCp.Product__c = mcp.Product__c; 
                                newCp.Opportunity__c = oppId;
                                newCp.AddContractProduct__c = true;
                                newCp.SalesPrice__c = mcp.SalesPriceWT__c;
                                newCp.IsSycToNc__c = false;
                                newCp.RecordTypeId = rtShiji; 

                                newCps.add(newCp);

                            exitsList.add(new Measure_Calculate_Product__c(Id=mcp.Id,AppendState__c='已追加'));    
                         }
                        
                     }
                       if(newCps.size()>0)insert newCps;
                       update c;
                       //q.Contract__c = selectedCon;
                      opp.StageName = '合同签订';
                       //update q;
                       if (exitsList.size() > 0) update exitsList;
                      update opp;
                      Measure_Calculate__c mc = [select Id ,AddedContract__c from Measure_Calculate__c where Id =: mcid];
                        mc.AddedContract__c = selectedCon;
                        update mc ;
                        msg = msg.length() > 0 ? '追加关联成功'+newCps.size() +'条合同产品! 下列测算产品已经存在合同中:'+ msg :'\t追加关联成功'+newCps.size() +'条合同产品!';
                     // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,msg ));

                }

    }
    public void appendQuoteProduct(){

         ///查询报价产品
        qProducts = [select product__c,Product__r.Name,Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c,SalesPrice__c from QuoteProduct__c where Quote__c =: qid ];
          for(QuoteProduct__c q: qProducts){
            qps.put(q.Product__c ,q.Product__c);
        }
         List<ContractProduct__c> newCps = new List<ContractProduct__c>(); 
            Set<Id> temp = new Set<Id>();
            List<QuoteProduct__c> exitsList = new List<QuoteProduct__c>();
                if(selectedCon == null){//如果没有选择合同

                     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请选择要关联的合同!'));
                }else{

                     for(ContractProduct__c cp: [select Product__c,Product__r.Name from ContractProduct__c where contract__c =: selectedCon]){
                        if(qps.containsKey(cp.Product__c)){
                            temp.add(cp.Product__c);
                        }   
                    }

                   
                    Id rtShiji = Utils.getRecordTypeIdByDevNameAndObjName('ReagentContractProduct','ContractProduct__c');

                   Contract__c c = [select Id,AddContractProduct__c from Contract__c where Id =: selectedCon];
                   c.AddContractProduct__c = true;
                     for(QuoteProduct__c q : qProducts){
                     
                         if (temp.contains(q.Product__c)) {
                            msg += q.Product__r.Brand__c +'-'+ q.Product__r.Name +'-' +q.Product__r.Spec__c+'*'+q.Product__r.SerialNo__c + ';\r\n';
                           exitsList.add(new QuoteProduct__c(Id=q.Id,AppendState__c='与合同产品重复，未追加'));    

                             continue;
                         }else{
                           ContractProduct__c newCp = new ContractProduct__c();
                                newCp.Contract__c = selectedCon;
                                newCp.Product__c = q.Product__c; 
                                newCp.Opportunity__c = oppId;
                                newCp.AddContractProduct__c = true;
                                newCp.SalesPrice__c = q.SalesPrice__c;
                                newCp.IsSycToNc__c = false;
                                newCp.RecordTypeId = rtShiji; 

                                newCps.add(newCp);

                            exitsList.add(new QuoteProduct__c(Id=q.Id,AppendState__c='已追加'));    
                         }
                        
                     }
                       if(newCps.size()>0)insert newCps;
                       update c;
                       q.Contract__c = selectedCon;
                       opp.StageName = '合同签订';
                       update q;
                       if (exitsList.size() > 0) update exitsList;
                      update opp;
                        msg = msg.length() > 0 ? '追加关联成功'+newCps.size() +'条合同产品! 下列报价产品已经存在合同中:'+msg : '\t追加关联成功'+newCps.size() +'条合同产品!';
                     // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,msg ));

                }
    }
    public void save(){
        if (((mcid != null && opp.StageName != '合同签订') || (qid != null  && opp.StageName != '方案谈判'  && opp.StageName != '招标')) && !Test.isRunningTest()) {
            
           if(mcid != null)msg =  '只有业务机会为在"合同签订"阶段才能追加测算试剂产品到合同';
           if(qid != null)msg ='只有业务机会为在 "方案谈判" "招标" 阶段才能追加试剂产品到合同';
            return  ;
        }

        SavePoint sp = Database.setSavepoint();
        try {
               if(qid != null) appendQuoteProduct();
                if(mcid != null) appendMeasrueCalcProduct();
                backId = selectedCon;
        }catch (Exception e) {
          Database.rollback(sp);
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));

        }
    
     

    }

}